package imdbfolder.communications;

import java.io.IOException;

//import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;

public class HttpRequester {
    public HttpRequester() {
        super();
    }

    public String getHttpResult(String urlString) throws HttpRequesterException {
        HttpClient client = new HttpClient();
        
        GetMethod getMethod = new GetMethod(urlString);
        
        String responseBody = null;
    
        // This can be used to (try) to fetch titles in another language then English, seems to work only in German/Spanish/French       
        // getMethod.setRequestHeader( new Header( "Accept-Language", "de-DE,en;q=0.9,de;q=0.8" ) );
        
        int statusCode;
        try {
            statusCode = client.executeMethod(getMethod);
            
            if(statusCode == HttpStatus.SC_OK) {
                responseBody = new String(getMethod.getResponseBody());
            }
            else {
                throw new HttpRequesterException("Request failed with " + statusCode + ": " + getMethod.getStatusText());
            }
        }
        catch (HttpException e) {
            throw new HttpRequesterException(e);
        }
        catch (IOException e) {
            throw new HttpRequesterException(e);
        }
        finally {
            getMethod.releaseConnection();
        }
        
        return responseBody;
    }

}